package org.teiid.translator.cassandra.metadata;

import java.util.ArrayList;
import java.util.List;

import org.teiid.metadata.MetadataFactory;
import org.teiid.metadata.Table;
import org.teiid.query.sql.symbol.Array;
import org.teiid.translator.TypeFacility;

import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.TableMetadata;

/**
 * 
 * @author Kouba
 *
 */
public class CassandraMetadataProcessor {
	private MetadataFactory metadataFactory;
	private KeyspaceMetadata keyspaceMetadata;
	
	public CassandraMetadataProcessor(MetadataFactory factory, KeyspaceMetadata keyspaceInfo){
		this.metadataFactory = factory;
		this.keyspaceMetadata = keyspaceInfo;
	}
	
	/**
	 * Creates metadata from all column families in current keyspace.
	 */
	public void processMetadata() {
		for (TableMetadata columnFamily : keyspaceMetadata.getTables()){
			addTable(columnFamily);
		}
		
	}

	/**
	 * Adds table.
	 * @param columnFamily
	 */
	private void addTable(TableMetadata columnFamily) {
		Table table = metadataFactory.addTable(columnFamily.getName());
		addColumnsToTable(table, columnFamily);
		addPrimaryKey(table, columnFamily);
	}

	/**
	 * Adds a primary key from columnFamily to given table.
	 * @param table			Teiid table
	 * @param columnFamily
	 */
	private void addPrimaryKey(Table table, TableMetadata columnFamily) {
		List<ColumnMetadata> primaryKeys = new ArrayList<ColumnMetadata>();
		primaryKeys = columnFamily.getPrimaryKey();
		List<String> PKNames = new ArrayList<String>();
		PKNames.add(primaryKeys.get(0).getName());
		metadataFactory.addPrimaryKey("PK_" + columnFamily.getName(), PKNames, table);
		
	}

	/**
	 * Adds all columns of column family.
	 * @param table			Teiid table
	 * @param columnFamily	
	 */
	private void addColumnsToTable(Table table, TableMetadata columnFamily) {
		for (ColumnMetadata column : columnFamily.getColumns()){
			
			Class<?> cqlTypeToJavaClass = column.getType().asJavaClass();
			Class<?> teiidRuntimeTypeFromJavaClass = TypeFacility.getRuntimeType(cqlTypeToJavaClass);
			String type = TypeFacility.getDataTypeName(teiidRuntimeTypeFromJavaClass);
			
			org.teiid.metadata.Column c = metadataFactory.addColumn(column.getName(), type, table);
		}
		
	}

}
